package com.chenjj.java.juc.tools.cyclicbarrier;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 游客
 */
public class Tourist implements Runnable{

    private String name;
    private CyclicBarrier cyclicBarrier;

    private Tourist(){}

    public Tourist(String name, CyclicBarrier cyclicBarrier) {
        this.name = name;
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        Random random = new Random();
        System.out.println("游客"+name+"正在参观景点A..");
        long s = System.currentTimeMillis();
        try {
            Thread.sleep((int)Math.floor((random.nextDouble()*10000.0)));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long e = System.currentTimeMillis();
        System.out.println("游客"+name+"参观景点A完毕，耗时：" + (e - s) + "ms");
        try {
            cyclicBarrier.await();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        } catch (BrokenBarrierException e1) {
            e1.printStackTrace();
        }

        System.out.println("游客"+name+"正在参观景点B..");
        long s1 = System.currentTimeMillis();
        try {
            Thread.sleep((int)Math.floor((random.nextDouble()*10000.0)));
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        long e1 = System.currentTimeMillis();
        System.out.println("游客"+name+"参观景点B完毕，正在集合点等待，耗时：" + (e1 - s1) + "ms");
        try {
            cyclicBarrier.await();
        } catch (InterruptedException e2) {
            e2.printStackTrace();
        } catch (BrokenBarrierException e2) {
            e2.printStackTrace();
        }

        System.out.println("游客"+name+"正在参观景点C..");
        long s2 = System.currentTimeMillis();
        try {
            Thread.sleep((int)Math.floor((random.nextDouble()*10000.0)));
        } catch (InterruptedException e2) {
            e2.printStackTrace();
        }
        long e2 = System.currentTimeMillis();
        System.out.println("游客"+name+"参观景点C完毕，耗时：" + (e2 - s2) + "ms");
        try {
            cyclicBarrier.await();
        } catch (InterruptedException e3) {
            e3.printStackTrace();
        } catch (BrokenBarrierException e3) {
            e3.printStackTrace();
        }
        System.out.println("所有景点参观完毕，回家！");

    }
}
